import { http } from '@/utils/http'

export interface CourseWareItem {
  categoryId: number
  duration: number | null
  fileName: string
  fileSize: number
  isDelete: number
  lastUpdateTime: string
  lookCount: number
  loveCount: number
  packId: string
  path: string
  picUrl: string
  roleTags: string | null
  score: number
  tags: string
  type: number
  userId: number
  wareDesc: string
  wareId: number
  wareName: string
  wareSort: number
  wareTypes: number
  wareType: number
  minimumTimes: number
  needStudyTimes: number
  learnProcess: number
  progress: number
  minimumTime: number
  isShowWeChat: number
  categoryName: string | null
  isRootWare: boolean
  courseWarePackageId: number
}

/* 获取课件列表 */
export const getCourseWareList = (
  id?: number, // 对应resId
  recordId?: number,
): Promise<IResData<CourseWareItem[]>> => {
  return http.get<CourseWareItem[]>('/api/MP/GetCourseWare', {
    id,
    recordId,
  })
}

export interface CourseWare {
  categoryId: number
  duration: number | null
  fileName: string
  fileSize: number
  isDelete: number
  lastUpdateTime: string
  lookCount: number
  loveCount: number
  packId: string
  path: string
  picUrl: string
  roleTags: string | null
  score: number
  tags: string
  type: number
  userId: number
  wareDesc: string
  wareId: number
  wareName: string
  wareSort: number
  wareTypes: number
  isRootWare: boolean
  courseWarePackageId: number
  wareType: number
  categoryName: string
}

export interface Len {
  attemptId: number
  id: number
  lastUpdateTime: string
  minimumTimes: number
  progress: number
  progressPercent: number
  recordId: number
  userId: number
  wareId: number
  wareType: number
}

export interface CourseWareData {
  result: number
  courseware: CourseWare
  len: Len
}

/* 课件 */
export const getCourseWare = (wareid: number): Promise<IResData<CourseWareData>> => {
  return http.get<CourseWareData>('/api/MP/GetWare?wareid=' + wareid)
}

export interface VideoFileUrl {
  ConvertFileUrl: string
  FileId: string
  FileUrl: string
  Id: string
  PackId: string
  PicUrl: string
}

export interface VideoFile {
  ConvertFilePath: string
  Converttime: string
  FilePath: string
  FileType: string
  Filename: string
  Groupname: string
  Id: string
  Introduction: string
  IsConvert: string
  IsDelete: string
  KeyPoint: string
  LearnDuration: string
  OtherInformation: string
  PicPath: string
  Resolution: string
  ServerType: string
  Suffix: string
  UploadUser: string
  Uploadtime: string
  Url: VideoFileUrl[]
}

export interface VideoFileResponse {
  RecordCount: number
  DataList: VideoFile[]
  Message: string
}

/* 获取课件中的视频文件 */
export const getVideoFile = (Id: number, callback?: string): Promise<VideoFileResponse> => {
  return new Promise<VideoFileResponse>((resolve, reject) => {
    uni.request({
      // url: 'https://grundfosfile.elearningcn.com/FS/FileGet',
      url: 'https://cpbuat.panzhi.com.cn:8266/FS/FileGet',
      method: 'GET',
      data: {
        Id,
      },
      dataType: 'json',
      success: (res) => {
        const data = res.data as VideoFileResponse
        if (data.RecordCount > 0) {
          resolve(data)
        } else {
          uni.showToast({
            icon: 'none',
            title: data.Message || '请求错误',
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
        })
        reject(err)
      },
    })
  })
}

export interface CourseDetails {
  recordId: number
  sourceId: number
  levelDesc: string
  frontImageUrl: string
  isLike: boolean
  isCollection: boolean
  learnUserCount: number
  openDepts: number[]
  openDeptsOption: number[]
  openPostsOption: any[]
  openClassOption: any[]
  openPosts: any[]
  openClass: any[]
  avgScore: number
  categoryId: number
  cateTag: string
  collection_num: number
  comment_num: number
  courseCode: string
  courseCommentCredit: string
  courseCredit: string
  courseId: number
  courseName: string
  courseType: number
  createTime: string
  createUser: number
  credit_dayafter: number
  credit_daybefore: number
  credit_testgood: number
  crowd: any
  day_after: number
  day_before: number
  firstPublishTime: string
  frontImage: string
  isBasic: any
  isPublic: number
  isPublish: number
  isShowWeChat: number
  lastPublishTime: string
  lastUpdateTime: string
  learnScore: number
  learnTime: number
  like_num: number
  look_num: number
  lookup: string
  openCrowd: string
  openCrowdOption: string
  outline: string
  overTime: string
  padBigImg: string
  padImage: any
  padSmallImg: string
  phoneBigImg: string
  phoneImage: any
  phoneSmallImg: string
  price: number
  queryDeptIds: string
  roleTags: string
  scoreCount: number
  status: number
  tags: string
  time_testgood: number
  learnProcess: number
  studyEndTime: any
  studyStartTime: any
  categoryName: any
  optionKey: number
}

export interface WareItem {
  categoryId: number
  duration: number | null
  fileName: string
  fileSize: number
  isDelete: number
  lastUpdateTime: string
  lookCount: number
  loveCount: number
  packId: string
  path: string
  picUrl: string
  roleTags: string
  score: number
  tags: string
  type: number
  userId: number
  wareDesc: string
  wareId: number
  wareName: string
  wareSort: number
  wareTypes: number
  wareType: number
  minimumTimes: number
  needStudyTimes: number
  learnProcess: number
  progress: number
  minimumTime: number
  isShowWeChat: number
  categoryName: string | null
  isRootWare: boolean
  courseWarePackageId: number
}

/**
 * 考试项目接口
 */
export interface ExamItem {
  /** 用户ID */
  senduserId: number
  /** 考试标题 */
  examTitle: string
  /** 允许考试次数 */
  allowTimes: number
  /** 考试时长(分钟) */
  timeLength: number
  /** 试卷ID */
  exampaperId: number
  /** 已考试次数 */
  testTimes: number
  /** 分数 */
  score: number
  /** 考试标志 */
  examFlag: number
  /** 是否可以进入考试 0-不可以 1-可以 */
  isCanGo: number
  /** 总分 */
  totalScore: number
  /** 及格分数 */
  passScore: number
  /** 是否通过考试 */
  isPass: boolean
  /** 考试时间范围 */
  examTime: string
  /** 开始时间 */
  beginTime: string
  /** 结束时间 */
  endTime: string
}

export interface CourseDetailsData {
  course: CourseDetails
  creditValue: string
  creditCommentValue: string
  wareList: WareItem[]
  examList: ExamItem[]
  allowExaminationCoursePercent: number
}

/* 根据id获取课程详情 */
export const getCourseDetails = ({
  id,
  LearnPath,
  SourceId,
  flex,
}: {
  id: number
  LearnPath?: number
  SourceId?: number
  flex?: number
}): Promise<IResData<CourseDetailsData>> => {
  return http.get<CourseDetailsData>('/api/MP/GetCourse', {
    id,
    LearnPath,
    SourceId,
    flex,
  })
}

/**
 * 进入考试请求返回的数据接口
 */
export interface GoInExamResult {
  /** 考试用户ID */
  senduserId: number
}

/**
 * 进入考试
 * @param courseId 课程ID
 * @param recordId 记录ID
 * @param exampaperId 试卷ID
 * @returns 包含senduserId的响应数据
 */
export function goInExam(
  courseId: number,
  recordId: number,
  exampaperId: number,
): Promise<IResData<GoInExamResult>> {
  return http.get<GoInExamResult>('/api/MP/GoInExam', {
    courseId,
    recordId,
    exampaperId,
  })
}

export interface UpdateProgressData {
  result: number
  percent: number
}

interface UpdateProgressParams {
  courseId: number
  progress: number
  allprogress: number
  wareId: number
  wareRecordId: number
}
// 更新学习进度
export const updateProgress = ({
  courseId,
  wareRecordId,
  progress, // 当前视频进度
  allprogress, // 视频总时长
}: {
  courseId?: number
  wareRecordId?: number
  progress?: number
  allprogress?: number
}): Promise<IResData<UpdateProgressData>> => {
  return http.get<UpdateProgressData>('/api/MP/RecordLearnWareProcess', {
    courseId,
    wareRecordId,
    allprogress,
    progress,
  })
}

/* 更新课件学习时间 */
export const updateMinimumTime = ({
  courseId,
  wareRecordId,
  timeLen,
}: {
  courseId: number
  wareRecordId: number
  timeLen: number
}): Promise<IResData<null>> => {
  return http.post<null>('/api/MP/RecordMinimumTime', {
    courseId,
    wareRecordId,
    timeLen,
  })
}
/* 课程是否完成 */
export const getCourseIsPass = (courseId: number): Promise<IResData<boolean>> => {
  return http.get<boolean>('/api/MP/GetCourseIsPass', {
    courseId,
  })
}
